package com.ruoyi.patrol.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.patrol.domain.PtCatalog;
import com.ruoyi.patrol.domain.TreeStruct;
import com.ruoyi.patrol.service.IPtCatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zyh
 */
@RestController
@RequestMapping("/resource/catalog")
public class PtCatalogController extends BaseController {

    @Autowired
    private IPtCatalogService catalogService;

    /**
     * 获取目录树形结构
     * @return
     */
    @GetMapping("tree")
    public AjaxResult catalogTree() {

        List<PtCatalog> list = catalogService.selectCatalogList();

        List<PtCatalog> treeList = catalogService.buildCatalogTree(list);
        return AjaxResult.success(treeList);
    }

    /**
     * 获取目录结构（id和label）
     * @return
     */
    @GetMapping("treeStruct")
    public AjaxResult catalogTreeStruct() {
        List<PtCatalog> list = catalogService.selectCatalogList();
        List<PtCatalog> treeList = catalogService.buildCatalogTree(list);

        List<TreeStruct> treeStruct = treeList.stream().map(TreeStruct::new).collect(Collectors.toList());
        return AjaxResult.success(treeStruct);
    }

    /**
     * 新增目录
     * @param catalog
     * @return
     */
    @PostMapping("/save")
    public AjaxResult save(@RequestBody PtCatalog catalog) {
        int row =catalogService.insertCatalog(catalog);
        return toAjax(row);
    }

    /**
     * 目录详情
     * @param catId
     * @return
     */
    @GetMapping("/info/{catId}")
    public AjaxResult getInfo(@PathVariable("catId") Long catId) {
        PtCatalog catalog = catalogService.getCatalogByCatId(catId);

        return AjaxResult.success(catalog);

    }

    /**
     * 更新目录
     * @param catalog
     * @return
     */
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody PtCatalog catalog) {
        int row = catalogService.updateCatalog(catalog);
        return toAjax(row);
    }

    /**
     * 删除目录
     * @param catId
     * @return
     */
    @DeleteMapping("delete/{catId}")
    public AjaxResult delete(@PathVariable("catId") Long catId) {
        // 判断是否有子目录
        boolean flag = catalogService.hasChildByCatId(catId);
        if(flag) {
            return error("当前目录存在子目录，不允许删除");
        }

        // 判断是否关联项目 todo

        int row = catalogService.deleteByCatId(catId);
        return toAjax(row);
    }

}
